<?php

namespace app\api\controller;

use think\Controller;
use think\facade\App;

class Coach extends Auth
{

    public function __construct()
    {
        parent::__construct();
        if ($this->role != 2) {
            $this->initreturn('越权操作');
        }
    }

    public function orderList()
    {
        $get = input('get.');
        $where = [];
        if (!empty($get['provinceid'])) {
            $where[] = ['coachprovinceid', '=', $get['provinceid']];
        } else if (!empty($get['longitude']) && !empty($get['latitude'])) {
            $longitude = $get['longitude'];
            $latitude = $get['latitude'];
        } else if (!empty($get['address'])) {
            $result = $this->getgaode($get['address']);
            if ($result['code'] == 1000) {
                if (!empty($result['data'])) {
                    $location = $result['data'];
                    $longitude = empty($location[0]) ? '' : $location[0];
                    $latitude = empty($location[1]) ? '' : $location[1];
                }
            } else {
                return $this->json($result['data'], $result['code'], $result['msg']);
            }
        }

        $where[] = ['isdel', '=', 0];
        $where[] = ['status', '=', 1];
        $where[] = ['issuing', '<>', $this->userid];
        $data['where'] = $where;
        $tableName = 'order';

        /*距离排序*/
        if (!empty($longitude) && !empty($latitude)) {
            /*需要传入经纬度，默认正序*/
            $data['field'] = "*, (st_distance(point (longitude,latitude), point (" . htmlspecialchars($longitude) . "," . htmlspecialchars($latitude) . "))*111195/1000 ) as distance";
            $data['order'] = 'distance asc';
        }

        $data['totalCount'] = $this->countTable($tableName, $data);
        $data = $this->buildCount($data);
        $list = $this->listTable($tableName, $data);

        $member = $this->listTable('member', [
            'where' => [
                ['memberid', 'in', array_column($list, 'memberid')],
            ],
            'field' => 'memberavatar,membertruename,memberbirthday,memberid,membersex,memberage',
        ]);

        $apply = $this->listTable('apply_order', ['where' => [
            ['coachid', "=", $this->userid],
            ['orderid', "in", array_column($list, 'orderid')],
        ], 'field' => 'orderid']);


        foreach ($list as $key => $val) {
            $list[$key]['addtime'] = empty($val['addtime']) ? '' : date('Y-m-d H:i:s', $val['addtime']);
            $list[$key]['updatetime'] = empty($val['updatetime']) ? '' : date('Y-m-d H:i:s', $val['updatetime']);
            foreach ($member as $v) {
                if ($v['memberid'] == $val['memberid']) {
                    $list[$key]['membertruename'] = $v['membertruename'];
                    $list[$key]['memberavatar'] = $v['memberavatar'];
                    $list[$key]['membersex'] = $v['membersex'];
                    $list[$key]['memberage'] = empty($v['memberbirthday']) ? (empty($v['memberage']) ? '暂无' : $v['memberage']) : birthday($v['memberbirthday']);
                }
            }

            $list[$key]['isapply'] = 0;
            foreach ($apply as $av) {
                if ($av['orderid'] == $val['orderid']) {
                    $list[$key]['isapply'] = 1;
                }
            }
        }
        $data['data'] = $list;
        return $this->json($data);
    }


    /**
     * 教练信息编辑
     */
    public function updateCoachInfo()
    {
        $post = input('post.');

        $arr = ['coachnickname', 'coachtruename', 'coachavatar', 'coachbirthday', 'coachage', 'coachsex', 'homeaddress', 'coacheqq', 'coachdesc'];
        $data = [];
        foreach ($arr as $key => $val) {
            if (isset($post[$val])) {
                $data[$val] = empty($post[$val]) ? '' : $post[$val];
            }
        }

        if (empty($data)) {
            return $this->json($this->userid, 1000, '编辑成功');
        }

        $where = ['coachid' => $this->userid];
        $update = [
            'where' => $where,
            'data' => $data,
        ];

        $ans = $this->updateTable('coach', $update);

        if (!empty($data['coachtruename'])) {
            $yx = new \app\common\lib\YxUtils();
            $yx->updateUinfo($this->table . '_' . $this->userid, $data['coachtruename']);
        }

        if ($ans) {
            return $this->json($ans, 1000);
        } else {
            return $this->json($ans, 2000);
        }
    }

    /**
     * 更新教练
     */
    public function updateDrivInfo()
    {
        $post = input('post.');

        $arr = ['school' => '驾校', 'coachprovinceid' => '省份', 'coachcityid' => '市级', 'coachaddressinfo' => '驾校地址', 'seniority' => '资历', 'license' => '驾驶证号码', 'faceidcard' => '身份证正面照', 'backidcard' => '身份证反面照', 'holdingimg' => '手持身份证图片', 'licenseimg' => '驾驶证图片'];

        $noarr = ['coachareaid' => '区级', 'addressimg' => '驾驶场地图片', 'drivingimg' => '行驶证图片', 'qualificationimg' => '资格证图片', 'postimg' => '上岗证图片', 'coachingimg' => '教练证图片', 'otherimg' => '其他证图片'];
        $in_array = array_merge(array_keys($arr), array_merge($noarr));

        $where = ['coachid' => $this->userid];
        $info = $this->findTable('coach', ['where' => $where]);
        if (empty($info)) {
            return $this->json($this->userid, 1000, '无效编辑');
        }

        if ($info['status'] == 1) {
            foreach ($arr as $key => $val) {
                if (empty($post[$key])) {
                    return $this->json($post, 1000, '请输入正确' . $val);
                }
            }
        }

        $data = [];
        foreach ($in_array as $val) {
            if (isset($post[$val])) {
                $data[$val] = empty($post[$val]) ? '' : $post[$val];
            }
        }

        if (empty($data)) {
            return $this->json($this->userid, 1000, '编辑成功');
        }

        if (!empty($post['longitude']) && !empty($post['latitude'])) {
            $data['longitude'] = $post['longitude'];
            $data['latitude'] = $post['latitude'];
        }

        if (empty($data['longitude']) || empty($data['latitude'])) {
            $address = $data['coachaddressinfo'];
            $result = $this->getgaode($address);
            if ($result['code'] == 1000) {
                if (!empty($result['data'])) {
                    $location = $result['data'];
                    $data['longitude'] = empty($location[0]) ? '' : $location[0];
                    $data['latitude'] = empty($location[1]) ? '' : $location[1];
                }
            } else {
                return $this->json($result['data'], $result['code'], $result['msg']);
            }
        }

        $data['status'] = 2;
        $where = ['coachid' => $this->userid];
        $update = [
            'where' => $where,
            'data' => $data,
        ];

        $ans = $this->updateTable('coach', $update);

        if ($ans) {
            return $this->json($ans, 1000);
        } else {
            return $this->json($ans, 2000);
        }
    }

    public function addOrder()
    {

        $post = input('post.');

        $builarr = ['trainingcourse' => '培训科目', 'trainingmodel' => '培训车型', 'examinecity' => '考试城市', 'collegename' => '学员姓名', 'collegemobile' => '学员手机', 'collegeage' => '学员年龄', 'collegeaddress' => '地址', 'province' => '省份'];

        $data = [];
        foreach ($builarr as $key => $val) {
            if (empty($post[$key])) {
                return $this->json($post, 2000, '请输入正确' . $val);
            }
            $data[$key] = empty($post[$key]) ? '' : $post[$key];
        }

        if ((int) $data['collegeage'] < 18 || (int) $data['collegeage'] > 70) {
            return $this->json($post, 2000, '驾照最低的年龄要求在18周岁以上，70周岁以下年龄');
        }

        if (empty($post['collegedetailedaddress'])) {
            return $this->json($post, 2000, '请输入详细地址');
        }

        if (empty($post['amount']) || (float) ($post['amount']) <= 0) {
            return $this->json($post, 2000, '请输入正确的单价');
        }

        $data['amount'] = (float) $post['amount'];
        $data['collegedetailedaddress'] = $post['collegedetailedaddress'];

        if ($this->user['coachmobile'] == $data['collegemobile']) {
            return $this->json($post, 2000, '请输入正确学员手机号码，非教练手机号码');
        }

        $memberinfo = $this->findTable('member', ['where' => ['membermobile' => $data['collegemobile']]]);

        if (!empty($memberinfo) && $memberinfo['status'] == 1) {
            return $this->json($post, 2000, '该用户已存在,无法代发单');
        }

        $info = $this->findTable('order', ['where' => [
            ['collegemobile', '=', $data['collegemobile']],
            ['isdel', '=', 0],
            ['status', '<', 6]
        ]]);

        if (!empty($info)) {
            return $this->json($post, 2000, '该用户已存在未完成的订单，等待完成才能继续发单');
        }

        if (!empty($post['city'])) {
            $data['city'] = $post['city'];
        }

        if (!empty($post['area'])) {
            $data['area'] = $post['area'];
        }

        if (!empty($post['describe'])) {
            $data['describe'] = $post['describe'];
        }

        $ordersn = $this->createOrdersn();
        $data['ordersn'] = $ordersn . $this->userid;
        $data['isissuing'] = 1;
        $data['issuing'] = $this->userid;

        $address = $data['collegeaddress'] . $data['collegedetailedaddress'];
        $result = $this->getgaode($address);
        if ($result['code'] == 1000) {
            if (!empty($result['data'])) {
                $location = $result['data'];
                $data['longitude'] = empty($location[0]) ? '' : $location[0];
                $data['latitude'] = empty($location[1]) ? '' : $location[1];
            }
        } else {
            return $this->json($result['data'], $result['code'], $result['msg']);
        }

        if (!empty($post['longitude']) && !empty($post['latitude'])) {
            $data['longitude'] = $post['longitude'];
            $data['latitude'] = $post['latitude'];
        }

        $memberid = $this->addMember($data);
        if (!$memberid) {
            return $this->json([], 2000, '发单失败');
        }

        $data['memberid'] = $memberid;
        $ans = $this->insertTable('order', $data);
        if ($ans) {
            $time = date('Y-m-d H:i:s');
            $notice = [
                [
                    'type' => 2,
                    'userid' => 0,
                    'reciveutype' => 3,
                    'reciveuid' => $memberid,
                    'reciveutable' => 'member',
                    'msgtitle' => '发单成功',
                    'msgtext' => "您在{$time}发单成功,单号：{$data['ordersn']}, 请赶紧邀请教练进行学习"
                ],
                [
                    'type' => 2,
                    'userid' => 0,
                    'reciveutype' => 2,
                    'reciveuid' => $this->userid,
                    'reciveutable' => $this->table,
                    'msgtitle' => '代发单成功',
                    'msgtext' => "您在{$time}代学员{$data['collegename']}发单成功,单号：{$data['ordersn']}。"
                ],

            ];
            $this->addnotice($notice, "two");
            $this->addCustomer(['memberid' => $memberid, 'coachid' => $this->userid, 'source' => 3]);

            $params = [];
            $params['signName'] = '快通驾驶';
            $params['noticetemplateCode'] = config('param.alimess.noticetemplateCode');
            $mess = new Mess();
            $mess->sendNoticeByAli($data['collegemobile'], ['name' => $this->user['coachtruename']], $params);

            return $this->json($ans, 1001, '发单成功');
        } else {
            return $this->json($ans, 2000, '发单失败');
        }
    }

    public function addMember($param)
    {
        $where = ['membermobile' => $param['collegemobile']];
        $info = $this->findTable('member', ['where' => $where]);
        if (empty($info)) {
            $data = [
                'status' => 2,
                'membername' => $param['collegemobile'],
                'membermobile' => $param['collegemobile'],
                'membernickname' => $param['collegename'],
                'membertruename' => $param['collegename'],
                'memberavatar' => \think\facade\Request::domain(true) . '/public/static/member.png',
                'membercityid' => 0,
                'memberareaid' => 0,
                'membertownid' => 0,
                'memberaddressinfo' => $param['collegeaddress'],
            ];
            $ans = $this->insertTable('member', $data);
            return $ans;
        } else {
            return $info['memberid'];
        }
    }


    public function applyOrder()
    {
        $post = input('post.');

        if ($this->user['status'] == 1) {
            return $this->json($post, 2001);
        }

        if ($this->user['status'] == 2) {
            return $this->json($post, 2000, '需要等待审批通过后才能进行接单');
        }

        if (empty($post['orderid'])) {
            return $this->json([], 2000, '抢单参数错误');
        }
        $orderid = $post['orderid'];
        $where = ['orderid' => $orderid];

        $info = $this->findTable('order', ['where' => $where]);

        if (empty($info)) {
            return $this->json([], 2000, '订单不存在，请刷新重试');
        }

        if ($info['status'] > 1) {
            return $this->json([], 2000, '该订单已被接单');
        }

        if ($info['issuing'] == $this->userid) {
            return $this->json([], 2000, '您不能抢自己发的单哦');
        }

        $where = [
            'coachid' => $this->userid,
            'orderid' => $info['orderid'],
        ];
        $apply = $this->findTable('apply_order', ['where' => $where]);


        if (empty($apply)) {
            $data = [
                'orderid' => $info['orderid'],
                'ordersn' => $info['ordersn'],
                'coachid' => $this->userid,
                'coachtruename' => $this->user['coachtruename'],
            ];

            $ans = $this->insertTable('apply_order', $data);
            $this->addCustomer(['memberid' => $info['memberid'], 'coachid' => $this->userid, 'source' => 1]);

            if ($ans) {
                $time = date('Y-m-d H:i:s');
                $notice = [
                    'type' => 2,
                    'userid' => 0,
                    'reciveutype' => 3,
                    'reciveuid' => $info['memberid'],
                    'reciveutable' => 'member',
                    'msgtitle' => '教练' . $this->user['coachtruename'] . '申请订单',
                    'msgtext' => "{$time},您的订单：{$info['ordersn']}, 有一个新的申请教练， 申请教练：{$this->user['coachtruename']}"
                ];
                $this->addnotice($notice);
                return $this->json($ans, 1001, '提交成功');
            } else {
                return $this->json($ans, 2000, '提交失败');
            }
        } else {
            return $this->json([], 1000, '重复提交');
        }
    }

    public function getCustomerList()
    {
        $get = input('get.');

        $data = $where = [];
        if (!empty($get['begin']) && !empty($get['end'])) {
            $begin = strtotime($get['begin']);
            $end = strtotime(date('Y-m-d', strtotime('+1 day', $get['end'])));
            $where['addtime'] = ['between', [$begin, $end]];
        }

        $tableName = 'customer';
        $where['coachid'] = $this->userid;
        $data['where'] = $where;
        $data['tableName'] = $tableName;
        $data['totalCount'] = $this->countTable($tableName, $data);
        $data['order'] = 'addtime desc';
        $data = $this->buildCount($data);
        $list = $this->listTable($tableName, $data);

        if (!empty($list)) {
            $member = $this->listTable('member', [
                'where' => [
                    ['memberid', 'in', array_column($list, 'memberid')],
                ],
                'field' => 'memberavatar,membertruename,memberbirthday,memberid'
            ]);

            foreach ($list as $key => $val) {
                $list[$key]['addtime'] = empty($val['addtime']) ? '' : date('Y-m-d', $val['addtime']);
                $list[$key]['updatetime'] = empty($val['updatetime']) ? '' : date('Y-m-d', $val['updatetime']);
                foreach ($member as $v) {
                    if ($v['memberid'] == $val['memberid']) {
                        $list[$key]['membertruename'] = $v['membertruename'];
                        $list[$key]['memberavatar'] = $v['memberavatar'];
                        $list[$key]['age'] = empty($v['memberbirthday']) ? (empty($v['memberage']) ? '暂无' : $v['memberage']) : birthday($v['memberbirthday']);
                    }
                }
            }
        }

        $data['list'] = $list;
        return $this->json($data, 1000);
    }

    public function addBankCard()
    {
        $post = input('post.');

        if (empty($post['cardnumber'])) {
            return $this->json([], 2000, '请输入银行卡号');
        }

        $where = ['cardnumber' => $post['cardnumber'], 'table' => $this->table];
        $info = $this->findTable('bank_card', ['where' => $where]);

        if (!empty($info)) {
            return $this->json([], 2000, '银行卡已存在');
        }

        $data = [
            'cardnumber' => $post['cardnumber'],
            'table' => $this->table,
            'userid' => $this->userid
        ];

        $ans = $this->insertTable('bank_card', $data);

        if ($ans) {
            return $this->json($ans, 1001, '新增成功');
        } else {
            return $this->json($post, 2000, '新增失败');
        }
    }

    public function getBankCardList()
    {
        $get = input('get.');

        $data = $where = [];
        if (!empty($get['begin']) && !empty($get['end'])) {
            $begin = strtotime($get['begin']);
            $end = strtotime(date('Y-m-d', strtotime('+1 day', $get['end'])));
            $where[] = ['addtime', 'between', [$begin, $end]];
        }

        $where[] = ['userid', '=', $this->userid];
        $where[] = ['table', '=', $this->table];

        $data['where'] = $where;
        $data['tableName'] = 'bank_card';
        $data['order'] = 'addtime desc';
        $list = $this->listTable('bank_card', $data);

        foreach ($list as $key => $val) {
            $list[$key]['addtime'] = empty($val['addtime']) ? '' : date('Y-m-d H:i:s', $val['addtime']);
            $list[$key]['updatetime'] = empty($val['updatetime']) ? '' : date('Y-m-d H:i:s', $val['updatetime']);
        }
        $data['list'] = $list;
        return $this->json($data, 1000);
    }

    /**
     * 订单列表
     */
    public function orderCoachList()
    {
        $get = input('get.');

        $where = [
            ['coachid', '=', $this->userid],
        ];
        $applysql = $this->listTable('apply_order', ['where' => $where, 'field' => 'orderid', 'debug' => true, 'nolimit' => 1]);

        $where = [];
        if (empty($get['status']) || !in_array($get['status'], ['apply', 'await', 'complete', 'evaluate'])) {
            $where[] = \think\facade\Db::raw("(orderid in (" . $applysql . ")) or (status > 1 AND coachid = {$this->userid})");
        } else if ($get['status'] == 'apply') {
            $where[] =  ['', 'exp', \think\facade\Db::raw("(orderid in (" . $applysql . "))")];
        } else if ($get['status'] == 'await') {
            $where[] = ['status', 'in', [2, 3, 4, 5]];
            $where[] = ['coachid', '=', $this->userid];
        } else if ($get['status'] == 'complete') {
            $where[] = ['status', '=', 6];
            $where[] = ['coachid', '=', $this->userid];
        } else if ($get['status'] == 'evaluate') {
            $where[] = ['status', '=', 7];
            $where[] = ['coachid', '=', $this->userid];
        }

        $where[] = ['isdel', '=', 0];
        // $where[] = ['isissuing', '=', 0];
        $data['where'] = $where;
        $tableName = 'order';

        $data['totalCount'] = $this->countTable($tableName, $data);
        $data = $this->buildCount($data);
        $data['order'] = 'updatetime desc';
        $list = $this->listTable($tableName, $data);

        $member = $this->listTable('member', [
            'where' => [
                ['memberid', 'in', array_column($list, 'memberid')],
            ],
            'field' => 'memberavatar,membertruename,memberbirthday,memberid,membersex,memberage',
        ]);

        $order_timing = $this->listTable('order_timing', [
            'where' => [
                ['orderid', 'in', array_column($list, 'orderid')],
            ],
            'field' => 'endtime, orderid',
            'group' => 'orderid',
        ]);

        foreach ($list as $key => $val) {
            $list[$key]['addtime'] = empty($val['addtime']) ? '' : date('Y-m-d H:i:s', $val['addtime']);
            $list[$key]['updatetime'] = empty($val['updatetime']) ? '' : date('Y-m-d H:i:s', $val['updatetime']);
            $list[$key]['imgs'] = empty($val['imgs']) ? [] : explode(',', $val['imgs']);
            foreach ($member as $v) {
                if ($v['memberid'] == $val['memberid']) {
                    $list[$key]['membertruename'] = $v['membertruename'];
                    $list[$key]['memberavatar'] = $v['memberavatar'];
                    $list[$key]['membersex'] = $v['membersex'];
                    $list[$key]['age'] = empty($v['memberbirthday']) ? (empty($v['memberage']) ? '暂无' : $v['memberage']) : birthday($v['memberbirthday']);
                }
            }

            foreach ($order_timing as $tv) {
                if ($tv['orderid'] == $val['orderid'] && $val['status'] == 5) {
                    $list[$key]['countdown'] = timer($tv['endtime']);
                }
            }
        }
        $data['data'] = $list;
        return $this->json($data);
    }

    public function performance()
    {
        $data = $where = [];
        $where[] = ['coachid', '=', $this->userid];
        $where[] = ['status', '=', 1];
        $where[] = ['isdel', '=', 0];
        $data['where'] = $where;
        $data['tableName'] = 'performance';
        $data['totalCount'] = $this->countTable('performance', $data);
        $data = $this->buildCount($data);
        $data['order'] = 'addtime desc';
        $list = $this->listTable('performance', $data);

        $suma = $this->findTable('performance', ['where' => $where, 'field' => 'sum(amount) as sumamount']);
        $ywhere = $where;
        $ywhere[] = ['addtime', 'between', [strtotime(date("Y-m-d", strtotime("-1 day"))), time()]];
        $sumy = $this->findTable('performance', ['where' => $ywhere, 'field' => 'sum(amount) as sumamount']);


        $mwhere = $where;
        $mwhere[] = ['addtime', 'between', [date('Y-m-01'), time()]];
        $summ = $this->findTable('performance', ['where' => $mwhere, 'field' => 'sum(amount) as sumamount']);

        $member = $this->listTable('member', [
            'where' => [
                ['memberid', 'in', array_column($list, 'memberid')],
            ],
            'field' => 'memberavatar,membertruename,memberbirthday,memberid,membersex,memberage',
        ]);
        foreach ($list as $key => $val) {
            $list[$key]['addtime'] = empty($val['addtime']) ? '' : date('Y-m-d H:i:s', $val['addtime']);

            foreach ($member as $v) {
                if ($v['memberid'] == $val['memberid']) {
                    $list[$key]['membertruename'] = $v['membertruename'];
                    $list[$key]['memberavatar'] = $v['memberavatar'];
                    $list[$key]['membersex'] = $v['membersex'];
                    $list[$key]['age'] = empty($v['memberbirthday']) ? (empty($v['memberage']) ? '暂无' : $v['memberage']) : birthday($v['memberbirthday']);
                }
            }
        }

        $data['list'] = $list;
        $data['all'] = empty($suma['sumamount']) ? 0.00 : (float) $suma['sumamount'];
        $data['yesterday'] = empty($sumy['sumamount']) ? 0.00 : (float) $sumy['sumamount'];
        $data['month'] = empty($summ['sumamount']) ? 0.00 : (float) $summ['sumamount'];
        return $this->json($data, 1000);
    }


    public function businessManagement()
    {
        $data = $where = [];
        $where[] = ['coachid', '=', $this->userid];
        $where[] = ['status', '=', 1];
        $where[] = ['isdel', '=', 0];
        $suma = $this->findTable('performance', ['where' => $where, 'field' => 'sum(amount) as sumamount']);
        $twhere = $where;
        $twhere[] = ['addtime', 'between', [strtotime(date("Y-m-d")), time()]];
        $sumt = $this->findTable('performance', ['where' => $twhere, 'field' => 'sum(amount) as sumamount']);

        $mwhere = $where;
        $mwhere[] = ['addtime', 'between', [date('Y-m-01'), time()]];
        $summ = $this->findTable('performance', ['where' => $mwhere, 'field' => 'sum(amount) as sumamount']);

        $lmwhere = $where;
        $lmwhere[] = ['addtime', 'between', [mktime(0, 0, 0, date("m") - 1, 1, date("Y")), mktime(23, 59, 59, date("m"), 0, date("Y"))]];
        $sumlm = $this->findTable('performance', ['where' => $lmwhere, 'field' => 'sum(amount) as sumamount']);

        $data['allperformance'] = empty($suma['sumamount']) ? 0.00 : (float) $suma['sumamount'];
        $data['todayperformance'] = empty($sumt['sumamount']) ? 0.00 : (float) $sumt['sumamount'];
        $data['monthperformance'] = empty($summ['sumamount']) ? 0.00 : (float) $summ['sumamount'];
        $data['lastmonthperformance'] = empty($sumlm['sumamount']) ? 0.00 : (float) $sumlm['sumamount'];

        $order = $this->countTable('order', [
            'where' => [
                ['coachid', '=', $this->userid],
                ['isdel', '=', 0],
                ['status', '>', 1],
            ]
        ]);
        $data['paycustomer'] = $order;

        $customer = $this->countTable('customer', [
            'where' => [
                ['coachid', '=', $this->userid],
                ['isdel', '=', 0],
                ['status', '=', 1],
            ]
        ]);
        $data['totalcustomer'] = $customer;

        $mwhere = $where;
        $mwhere[] = ['addtime', 'between', [date('Y-m-01'), time()]];
        $summ = $this->findTable('performance', ['where' => $mwhere, 'field' => 'sum(amount) as sumamount']);

        $await = $this->findTable('withdrawal', ['where' => [
            ['status', '=', 1],
            ['isdel', '=', 0],
            ['coachid', '=', $this->userid],
        ], 'field' => 'sum(amount) as sumamount']);
        $data['awaitwithdrawal'] = empty($await['sumamount']) ? 0.00 : (float) $await['sumamount'];

        $processed = $this->findTable('withdrawal', ['where' => [
            ['status', '=', 2],
            ['isdel', '=', 0],
            ['coachid', '=', $this->userid],
        ], 'field' => 'sum(amount) as sumamount']);
        $data['processedwithdrawal'] = empty($processed['sumamount']) ? 0.00 : (float) $processed['sumamount'];
        return $this->json($data, 1000);
    }

    public function getInvitation()
    {
        $get = input('get.');

        $data = $where = [];
        if (!empty($get['begin']) && !empty($get['end'])) {
            $begin = strtotime($get['begin']);
            $end = strtotime(date('Y-m-d', strtotime('+1 day', $get['end'])));
            $where[] = ['addtime', 'between', [$begin, $end]];
        }

        $where[] = ['coachid', '=', $this->userid];
        $where[] = ['status', '=', 1];
        $where[] = ['isdel', '=', 0];
        $data['where'] = $where;
        $data['tableName'] = 'invitation';
        $data['totalCount'] = $this->countTable('invitation', $data);
        $data = $this->buildCount($data);
        $list = $this->listTable('invitation', $data);

        $member = $this->listTable('member', [
            'where' => [
                ['memberid', 'in', array_column($list, 'memberid')],
            ],
            'field' => 'memberavatar,membertruename,memberbirthday,memberid,membersex,memberage',
        ]);

        foreach ($list as $key => $val) {
            foreach ($member as $v) {
                if ($v['memberid'] == $val['memberid']) {
                    $list[$key]['membertruename'] = $v['membertruename'];
                    $list[$key]['memberavatar'] = $v['memberavatar'];
                    $list[$key]['membersex'] = $v['membersex'];
                    $list[$key]['age'] = empty($v['memberbirthday']) ? (empty($v['memberage']) ? '暂无' : $v['memberage']) : birthday($v['memberbirthday']);
                }
            }
            $list[$key]['addtime'] = empty($val['addtime']) ? '' : date('Y-m-d H:i:s', $val['addtime']);
        }
        $data['list'] = $list;
        return $this->json($data, 1000);
    }

    public function applyInvitation()
    {
        $post = input('post.');

        if ($this->user['status'] != 3) {
            return $this->json($post, 2000, '需要等待审批通过后才能接受邀请');
        }

        if (empty($post['id'])) {
            return $this->json([], 2000, '请求参数错误');
        }

        if (empty($post['status']) || !in_array($post['status'], [2, 3])) {
            return $this->json([], 2000, '请求参数错误');
        }

        $invitation = $this->findTable('invitation', ['where' => ['id' => $post['id'], 'coachid' => $this->userid]]);

        if (empty($invitation) || $invitation['status'] > 1) {
            return $this->json([], 2000, '该邀请已处理');
        }

        $orderid = $invitation['orderid'];
        $info = $this->findTable('order', ['where' => ['orderid' => $orderid]]);

        if (empty($info) || $info['status'] > 1) {
            $this->checkInvitation($post['id'], 3);
            return $this->json([], 2000, '该邀请已过期');
        }

        $where = [
            'coachid' => $this->userid,
            'orderid' => $info['orderid'],
        ];
        $apply = $this->findTable('apply_order', ['where' => $where]);

        $this->checkInvitation($post['id'], $post['status']);
        if (empty($apply)) {
            $data = [
                'orderid' => $info['orderid'],
                'ordersn' => $info['ordersn'],
                'coachid' => $this->userid,
                'coachtruename' => $this->user['coachtruename'],
                'type' => 2,
            ];

            $ans = $this->insertTable('apply_order', $data);
            $this->addCustomer(['memberid' => $info['memberid'], 'coachid' => $this->userid, 'source' => 1]);

            if ($ans) {
                return $this->json($ans, 1001, '提交成功');
            } else {
                return $this->json($ans, 2000, '提交失败');
            }
        } else {
            return $this->json([], 1000, '操作成功');
        }
    }

    public function checkInvitation($id, $status)
    {
        $where = [
            ['id', '=', $id],
        ];

        $update = [
            'where' => $where,
            'data' => [
                'status' => $status
            ],
        ];
        $ans = $this->updateTable('invitation', $update);
    }


    public function getApplyOrderList()
    {
        $where = ['coachid' => $this->userid, 'status' => 2];
        $info = $this->findTable('apply_order', [
            'where' => $where
        ]);

        if(! empty($info)) {
            $update = [
                'where' => $where,
                'data' => [
                    'status' => 3
                ],
            ];
            $this->updateTable('apply_order', $update);
            $bool = 1;
        } else {
            $bool = 0;
        }
        return $this->json($bool, 1000);
    }

    public function setInvitation()
    {
        $post = input('post.');
        if (empty($post['coachid'])) {
            return $this->json([], 2000, '参数错误');
        }

        if (empty($post['orderid'])) {
            return $this->json([], 2000, '参数错误');
        }

        $info = $this->findTable('order', ['where' => [
            ['orderid', '=', $post['orderid']],
            ['isdel', '=', 0],
            ['status', '=', 1],
        ]]);

        if (empty($info)) {
            return $this->json([], 2000, '无可邀请订单，请发单后再操作');
        }

        $coach = $this->findTable('coach', [
            'where' => [
                'coachid' => $post['coachid'],
            ],
            'field' => 'coachmobile',
        ]);

        if (empty($coach)) {
            return $this->json([], 2000, '教练账号异常，请邀请其他教练');
        }

        $where = [
            'coachid' => $post['coachid'],
            'orderid' => $info['orderid'],
        ];

        $invitation = $this->findTable('invitation', ['where' => $where]);

        if (empty($invitation)) {
            $data = [
                'memberid' => $info['memberid'],
                'coachid' => $post['coachid'],
                'orderid' => $info['orderid'],
            ];

            $ans = $this->insertTable('invitation', $data);
            if ($ans) {
                $params = [];
                $params['signName'] = '快通驾驶';
                $params['noticetemplateCode'] = "SMS_189032233";
                $mess = new Mess();
                $mess->sendNoticeByAli($coach['coachmobile'], ['consignee' => $this->user['membertruename'], 'number' => $this->user['membermobile']], $params);

                $time = date('Y-m-d H:i:s');
                $notice = [
                    'type' => 2,
                    'userid' => 0,
                    'reciveutype' => 2,
                    'reciveuid' => $post['coachid'],
                    'reciveutable' => 'coach',
                    'msgtitle' => '您有一条新的邀请',
                    'msgtext' => "您在{$time}有一条邀请订单，学员：{$this->user['membertruename']},联系方式：{$this->user['membermobile']}。"
                ];
                $this->addnotice($notice);
                return $this->json($ans, 1001, '邀请成功');
            } else {
                return $this->json($ans, 2000, '邀请失败');
            }
        } else {
            return $this->json([], 1000, '重复邀请');
        }
    }

    /**
     * 开始练车
     */
    public function confirmPractice()
    {
        $post = input('post.');

        if (empty($post['orderid'])) {
            return $this->json([], 2000, '订单参数错误');
        }
        $info = $this->findTable('order', ['where' => [
            ['isdel', '=', 0],
            ['status', '=', 3],
            ['orderid', '=', $post['orderid']],
        ]]);

        if (empty($info)) {
            return $this->json([], 2000, '暂无有效可练车订单');
        }

        if ($info['coachid'] != $this->userid) {
            return $this->json([], 2000, '无权限确认');
        }

        $where = ['orderid' => $post['orderid']];
        $update = [
            'where' => $where,
            'data' => [
                'status' => 4,
            ],
        ];

        $log = [
            'orderstatus' => 4,
            'orderid' => $post['orderid'],
            'userid' => $this->userid,
            'table' => $this->table,
            'desc' => "教练确认练车",
        ];

        \think\facade\Db::startTrans();
        try {
            $ans = $this->updateTable('order', $update); //订单
            $row = $this->setOrderTime($info);
            $log = $this->orderLog($log); ////记录
            // 提交事务
            if ($ans && $row && $log) {
                \think\facade\Db::commit();
                $time = date('Y-m-d H:i:s');
                $notice = [
                    'type' => 2,
                    'userid' => 0,
                    'reciveutype' => 3,
                    'reciveuid' => $info['memberid'],
                    'reciveutable' => 'member',
                    'msgtitle' => '订单开始练车',
                    'msgtext' => "{$time}，教练：{$this->user['coachtruename']} 已确认开始练车"
                ];
                $this->addnotice($notice);
                return $this->json($ans, 1001, '确认成功');
            } else {
                \think\facade\Db::rollback();
                return $this->json($ans, 2000, '确认失败');
            }
        } catch (\Exception $e) {
            // 回滚事务
            \think\facade\Db::rollback();
            return $this->json($ans, 2000, $e->getMessage());
        }
    }

    /**
     * 延期订单
     */
    public function delayOrder()
    {
        $post = input('post.');

        if (empty($post['orderid'])) {
            return $this->json([], 2000, '订单参数错误');
        }
        $info = $this->findTable('order', ['where' => [
            ['isdel', '=', 0],
            ['status', '=', 4],
            ['orderid', '=', $post['orderid']],
        ]]);

        if (empty($info)) {
            return $this->json([], 2000, '暂无有效可延期订单');
        }

        if ($info['coachid'] != $this->userid) {
            return $this->json([], 2000, '无权限确认');
        }

        $info = $this->findTable('order', ['where' => [
            ['orderid', '=', $post['orderid']],
        ]]);

        //更新订单
        $where = ['orderid' => $post['orderid']];
        $update = [
            'where' => $where,
            'data' => [
                'status' => 5,
            ],
        ];

        //订单记录写入
        $log = [
            'orderstatus' => 5,
            'orderid' => $post['orderid'],
            'userid' => $this->userid,
            'table' => $this->table,
            'desc' => "教练发起延期",
        ];

        \think\facade\Db::startTrans();
        try {
            $ans = $this->updateTable('order', $update); //订单
            $row = $this->setOrderTime($info, 1);
            $log = $this->orderLog($log); ////记录
            // 提交事务
            if ($ans && $row && $log) {
                $time = date('Y-m-d H:i:s');
                $notice = [
                    'type' => 2,
                    'userid' => 0,
                    'reciveutype' => 3,
                    'reciveuid' => $info['memberid'],
                    'reciveutable' => 'member',
                    'msgtitle' => '订单已被教练发起延期',
                    'msgtext' => "{$time}，订单已被延期，教练：{$this->user['coachtruename']} 已发起延期"
                ];
                $this->addnotice($notice);
                \think\facade\Db::commit();
                return $this->json($ans, 1001, '延期成功');
            } else {
                \think\facade\Db::rollback();
                return $this->json($ans, 2000, '延期失败');
            }
        } catch (\Exception $e) {
            // 回滚事务
            \think\facade\Db::rollback();
            return $this->json($ans, 2000, '延期失败');
        }
    }

    /**
     * 已完成订单
     */
    public function completeOrder()
    {
        $post = input('post.');

        if (empty($post['orderid'])) {
            return $this->json([], 2000, '订单参数错误');
        }
        $info = $this->findTable('order', ['where' => [
            ['isdel', '=', 0],
            ['status', 'in', [4, 5]],
            ['orderid', '=', $post['orderid']],
        ]]);

        if (empty($info)) {
            return $this->json([], 2000, '暂无有效可确认订单');
        }

        if ($info['coachid'] != $this->userid) {
            return $this->json([], 2000, '无权限确认');
        }

        $where = [];
        $where[] = ['orderid', '=', $post['orderid']];
        $where[] = ['status', 'in', [1, 3]];
        $order_timing = $this->findTable('order_timing', ['where' => $where]);

        $order_timing['coachid'] = $info['coachid'];
        $order_timing['memberid'] = $info['memberid'];
        $order_timing['amount'] = $info['amount'];

        $ans = $this->resultsEndTo($order_timing, 1);
        if ($ans) {
            $time = date('Y-m-d H:i:s');
            $notice = [
                'type' => 2,
                'userid' => 0,
                'reciveutype' => 3,
                'reciveuid' => $info['memberid'],
                'reciveutable' => 'member',
                'msgtitle' => '订单已完成',
                'msgtext' => "{$time}，订单已确认完成，教练：{$this->user['coachtruename']} 已确认"
            ];
            $this->addnotice($notice);
            return $this->json($ans, 1001, '订单确认完成');
        } else {
            return $this->json($ans, 2000, '操作失败');
        }
    }

}
